package com.huanbao.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huanbao.base.dto.LoginDto;
import com.huanbao.base.lang.Result;
import com.huanbao.entity.User;
import com.huanbao.service.UserService;
import com.huanbao.util.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * @description: 登录退出操作
 * @author: ZQ
 * @date: 2021-04-26-17:41
 */

@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AccountController {

    private final UserService userService;

    private final JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user, "用户不存在");
        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            return Result.fail("密码错误！");
        }
        String jwt = jwtUtils.generateToken(user.getId());
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");

        return Result.success(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .put("account", user.getAccount())
                .put("type", user.getType())
                .put("telephone", user.getTelephone())
                .put("address", user.getAddress())
                .map()
        );
    }

    /**
     * 退出登录
     *
     * @return 登出成功
     */
    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.success(200, "登出成功", null);
    }

    @GetMapping("/isExistUsername/{username}")
    public Result isExistUsername(@PathVariable("username") String username) {
        User one = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (null != one) return Result.success(false);
        return Result.success(true);
    }

}
